{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c7228d26",
   "metadata": {},
   "source": [
    "# 字典实践\n",
    "## 1.字典的实践（一）\n",
    "课本P112-P113：\n",
    "\n",
    "知识点：\n",
    "* 利用字典计算词频\n",
    "* 字典的初始化\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "7f578274",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "请输入一段文本，将统计元音字母出现的次数:hello world\n",
      "{'a': 0, 'e': 1, 'i': 0, 'o': 2, 'u': 0}\n"
     ]
    }
   ],
   "source": [
    "# 在列表的基础上（列表可统计出现的内容有哪些）\n",
    "# 字典可统计出现的内容+出现的次数\n",
    "vowels = [\"a\", \"e\", \"i\", \"o\", \"u\"]\n",
    "words = input(\"请输入一段文本，将统计元音字母出现的次数:\")\n",
    "found = {}\n",
    "\n",
    "# 创建字典：dict_name[key] = value\n",
    "# found[\"a\"]=0\n",
    "# found[\"e\"]=0\n",
    "# found[\"i\"]=0\n",
    "# found[\"o\"]=0\n",
    "# found[\"u\"]=0\n",
    "\n",
    "# 方法一：\n",
    "# for i in vowels:    # 可优化 fromkeys()\n",
    "#     found[i] = 0\n",
    "# print(found)\n",
    "\n",
    "# 方法二：利用fromkeys()实现初始化值\n",
    "found = found.fromkeys(vowels,0)\n",
    "\n",
    "for i in words:\n",
    "    if i in vowels:\n",
    "        found[i] +=1\n",
    "print(found)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8967216f",
   "metadata": {},
   "source": [
    "方法一：循环vowels"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e16c50ec",
   "metadata": {},
   "source": [
    "方法二：利用fromkeys 实现初始化值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "9417e6ae",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 0, 'e': 1, 'i': 0, 'o': 2, 'u': 0}\n"
     ]
    }
   ],
   "source": [
    "print(found)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9951c69e",
   "metadata": {},
   "source": [
    "* 字典的高级用法：fromkeys()\n",
    "> 1.给定一个序列数据作为key   \n",
    "> 2.把序列所有内容进行初始化，作为新字典的内容"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "10addd0d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Alex': 1, 'Marry': 1, 'Jack': 1, 'Jan': 1}"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "names_dict = [\"Alex\", \"Marry\", \"Jack\", \"Jan\"]\n",
    "names_age_dict = {}\n",
    "names_age_dict.fromkeys(names_dict,1)  # 把一个序列作为一个字典的keys，然后初始化其值（默认值为：None），可以给定一个值"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b0f53173",
   "metadata": {},
   "source": [
    "## 1.字典的实践（二）"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "992b46b9",
   "metadata": {},
   "source": [
    "* 字典的高级用法：setdefault()\n",
    "> 1.如果字典中还没有该内容（item）,新增该item作为字典的key，默认值default = None，可以指定值的内容（初始化值的内容）   \n",
    "> 2.如果该内容（item）已经是字典的key，则不操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "cc0bece7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 2, 'e': 0}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found = {'a':2}\n",
    "found.setdefault('e',0)  # e是不存在 found中的\n",
    "found"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "64644af6",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found.setdefault('a',5)  # a已经存在在 字典found的中了，不操作"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6a1ff656",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'a': 2, 'e': 0}"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "found"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "a905b05c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Provide a word to search for vowels:hello xiaoming\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{'e': 1, 'o': 2, 'i': 2, 'a': 1}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 课本字典实践二：hello xiaoming\n",
    "vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n",
    "word = input(\"Provide a word to search for vowels:\")\n",
    "found = {}\n",
    "\n",
    "for letter in word:\n",
    "    if letter in vowels:\n",
    "        found.setdefault(letter,0)  \n",
    "        found[letter] +=1\n",
    "found"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ccf842d6",
   "metadata": {},
   "source": [
    "### 课后实践：\n",
    "* 将字典的所有方法用表格形式做笔记\n",
    "\n",
    "| names | 说明 | 用法 | 使用结果 | 注意事项 |\n",
    "| :---: | :--- | :---: |   :---  | :---    |\n",
    "| clear()| 删除列表中的所有元素| c.clear()|空字典|-|\n",
    "| copy()| 返回字典的副本| c.copy()|复制某个字典|-|\n",
    "| fromkeys()| 返回拥有指定键和值的字典| c.fromkeys(keys,value)|-|keys必，指定新字典键的可迭代对象。value选，所有键的值,默认值是 None|\n",
    "| get()| 返回指定键的值| c.get(keyname, value)| 得到某个值| keyname必，要返回值的项目的键名。value选，如果指定的键不存在，则返回None|\n",
    "| items()| 返回包含每个键值对的元组的列表| c.items()| 包含字典的键值对的视图对象| 当字典中的项目值发生改变时，视图对象也会更新\n",
    "| keys()| 返回包含字典键的列表| c.keys()| 列表形式的字典键| 当在字典中添加项目时，视图对象也会更新|\n",
    "| pop()| 删除拥有指定键的元素| c.pop(keyname, defaultvalue)| 被删除项目的值是 pop() 方法的返回值|keyname必,需要删除项目的键名。defaultvalue选,返回值，假如指定的键不存在,如果未指定此参数，且未找到拥有指定键的项目，则会引发错误\n",
    "| popitem()| 删除最后插入的键值对| c.popitem()| 被删除项目是 pop() 方法的返回值|-|\n",
    "| setdefault()| 返回指定键的值| c.setdefault(keyname, value)|如果键不存在，则插入这个具有指定值的键|value如果键存在，则此参数无效。如果键不存在，则此值将成为键的值。|\n",
    "| update()| 使用指定的键值对字典进行更新| c.update(iterable)| 具有键值对的字典或可迭代对象，会被插入到字典中|-|\n",
    "| values()|\t返回字典中所有值的列表| c.values()| 列表形式的字典值| 当字典中的值改变时，视图对象也会更新|"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "c0e86b97",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 字典的实践（三）\n",
    "people = {}\n",
    "people['Ford'] = {\"Name\":'Ford Prefect',\n",
    "                  \"Gender\":'Male',\n",
    "                  \"Occupation\":'Researcher',\n",
    "                  \"Home Planet\":'Betelgeuse Seven'}\n",
    "people['Arthur'] = {\"Name\":'Arthur Dent',\n",
    "                  \"Gender\":'Male',\n",
    "                  \"Occupation\":'Sandwich-Maker',\n",
    "                  \"Home Planet\":'Earth'}\n",
    "people['Tricia'] = {\"Name\":'Tricia McMillan',\n",
    "                    \"Gender\":'Female',\n",
    "                    \"Occupation\":'Mathematician',\n",
    "                    \"Home Planet\":'Earth'}\n",
    "people['Marvin'] = {\"Name\":'Marvin',\n",
    "                    \"Gender\":'Unknown',\n",
    "                    \"Occupation\":'Paranoid Android',\n",
    "                    \"Home Planet\":'Unknown'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "894d4de9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Name': 'Tricia McMillan',\n",
       " 'Gender': 'Female',\n",
       " 'Occupation': 'Mathematician',\n",
       " 'Home Planet': 'Earth'}"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 请 找出 Tricia 的 名字全称\n",
    "people[\"Tricia\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ca609c6d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Tricia McMillan'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "people[\"Tricia\"][\"Name\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "5b5bb0d2",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Unknown'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "people['Marvin']['Home Planet']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "03910489",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['Ford', 'Arthur', 'Tricia', 'Marvin'])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查询字典中所有的key\n",
    "people.keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "b1901716",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values([{'Name': 'Ford Prefect', 'Gender': 'Male', 'Occupation': 'Researcher', 'Home Planet': 'Betelgeuse Seven'}, {'Name': 'Arthur Dent', 'Gender': 'Male', 'Occupation': 'Sandwich-Maker', 'Home Planet': 'Earth'}, {'Name': 'Tricia McMillan', 'Gender': 'Female', 'Occupation': 'Mathematician', 'Home Planet': 'Earth'}, {'Name': 'Marvin', 'Gender': 'Unknown', 'Occupation': 'Paranoid Android', 'Home Planet': 'Unknown'}])"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 查看字典中所有的value\n",
    "people.values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "18d66277",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
